<template>
  <a-spin :spinning="confirmLoading" class="spin-style">
    <j-form-container :disabled="formDisabled" style="width: 100%;">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-row>
              <a-col>
                <a-form-model-item label="添加方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="addByType">
                  <a-radio-group name="addByType" v-model="addByType">
                    <a-radio :value="1">手动绘制<span style="color: red;font-size: 12px;">(点击“开始绘制”按钮后，在地图上鼠标左键单击绘制路线，右键结束绘制)</span></a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col>
                <a-form-model-item label="道路编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                  <a-input v-model="model.code" placeholder="请输入道路编号"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col>
                <a-form-model-item label="道路名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roadName">
                  <a-input v-model="model.roadName" placeholder="请输入道路名称"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col>
                <a-form-model-item label="道路标签" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roadTag">
                  <!-- <j-dict-select-tag v-model="model.roadTag" title="请选择道路标签" dictCode="road_tag" placeholder="请选择道路标签"/> -->
                  <j-multi-select-tag
                    v-model="model.roadTag"
                    dictCode="road_tag"
                    placeholder="请选择">
                  </j-multi-select-tag>
                </a-form-model-item>
              </a-col>
             
              <a-col>
                <a-form-model-item label="示范区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="zoneId">
                  <j-dict-select-tag v-model="model.zoneId" title="请选择示范区" dictCode="demonstration_zone" placeholder="请选择示范区"/>
                </a-form-model-item>
              </a-col>
               <!-- 
              <a-col>
                <a-form-model-item label="示范区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="zoneName">
                  <a-input v-model="model.zoneName" placeholder="请输入示范区"  ></a-input>
                </a-form-model-item>
              </a-col> 
              -->
              <a-col>
                <a-form-model-item label="道路属性" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roadAttr">
                  <j-dict-select-tag v-model="model.roadAttr" title="请选择道路属性" dictCode="road_attr" placeholder="请选择道路属性"/>
                </a-form-model-item>
              </a-col>
              <a-col>
                <a-form-model-item label="道路类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roadType">
                  <j-dict-select-tag v-model="model.roadType" title="请选择道路类型" dictCode="road_type" placeholder="请选择道路类型"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="12">
            <a-row>
              <div style="width: 700px; height: 600px">
                <!-- <div id="map_canvas" style="width: 500px; height: 500px"></div> -->
                <BMap :pageHeight="550" ref="map" :zoom="12" @update-lineWkt="updateLineWkt"></BMap>
              </div>
            </a-row>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import BMap from '@/views/components/map/index.vue'
  import { gws84 } from '@/views/components/map/js/BD09-WGS84'

  export default {
    name: 'TRoadForm',
    components: {
      JDictSelectTag,
      BMap
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           code: [
              { required: true, message: '请输入道路编号!'},
           ],
           roadName: [
              { required: true, message: '请输入道路名称!'},
           ],
           roadTag: [
              { required: true, message: '请选择道路标签!'},
           ],
           zoneId: [
              { required: true, message: '请选择示范区!'},
           ],
           roadAttr: [
              { required: true, message: '请选择道路属性!'},
           ],
           roadType: [
              { required: true, message: '请选择道路类型!'},
           ],

        },
        url: {
          add: "/basicinfo/roadSurface/road/add",
          edit: "/basicinfo/roadSurface/road/edit",
          queryById: "/basicinfo/roadSurface/road/queryById"
        },
        addByType: 1
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
        this.model = {
          wkt: null
        };
        let lnglat = {"lng":this.$refs.map.mapCenter.lng, "lat":this.$refs.map.mapCenter.lat};
        this.$refs.map.setCenterAndZoom(lnglat, this.$refs.map.zoom);
        this.$refs.map.initDrawLineMode();
        // this.$refs.map.onclickEventDrawLine((e)=>{
        //   console.log(e);
        // })
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
        this.addPolylines(record);
        this.$refs.map.initDrawLineMode();
      },
      submitForm () {
        const that = this;
        if(!that.model.wkt){
          that.$message.warning("请右侧地图绘制道路!");
          return;
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      updateLineWkt(lineWkt){
        console.log('lineWkt: ', lineWkt);
        // console.log('this: ', this);
        this.model.wkt = lineWkt;
        console.log('this.model: ', this.model);
      },

      // 添加道路标记
      addPolylines(dataItem) {
        console.log('添加道路标记:', dataItem)
        if (!dataItem.wkt) {
          console.warn('道路缺少经纬度信息:', dataItem)
          return
        }
        let points = [];
        try {
          let wkt = dataItem.wkt;
          const xyArr = wkt.split(',');
          for (let i = 0; i < xyArr.length; i++) {
            const xy = xyArr[i].split(' ');
            const lng = parseFloat(xy[0]);
            const lat = parseFloat(xy[1]);
            // 坐标转换（如果需要）
            let coordinates = {
              lng: parseFloat(lng),
              lat: parseFloat(lat)
            }
            
            // 如果是WGS84坐标，需要转换为百度坐标
            if (dataItem.coordinateType === 'WGS84') {
              const gcj02Point = gws84().wgs84togcj02(coordinates.lng, coordinates.lat)
              coordinates = gws84().gcj02tobd09(gcj02Point.lng, gcj02Point.lat)
            }
            
            const point = new BMapGL.Point(coordinates.lng, coordinates.lat);
            points.push(point);
          }
        
          // 创建标记点
          let polyline = new BMapGL.Polyline(points, {
            strokeColor: "blue",
            strokeWeight: 2
          });
          this.$refs.map.polyline = polyline;
          this.$refs.map.map.addOverlay(polyline);    
          this.$refs.map.setViewportToPolyline(polyline);      
        } catch (error) {
          console.error('添加道路标记失败:', error, dataItem)
        }
      },
    }
  }
</script>
<style scoped>
  div.ant-modal, div.ant-modal-content {
      width: 1480px;
  }
  .spin-style{
      width: 1280px;
  }
  .tip-label-style{
    display: inline;
    width: 100%;
    text-align: center;
    font-size: 10px;
    color: red;
  }
  .area-select.medium{
    width: 100px;
  }
</style>